﻿using GKQC.Common;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Services;
using GKQC.Language;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace GKQC
{
    public partial class FormOrtDtlQuery : Form
    {
        UserModel user = null;
        AllDbContext dbContext = null;
        //List<LogModel> _Logs = null;
        FormStatus formStatus = FormStatus.Browser;
        readonly string countText = "記錄數：{0}";
        OrtService _OrtService = null;

        List<OrtDtlView> _Heads;

        public FormOrtDtlQuery(UserModel user, AllDbContext dbContext)
        {
            InitializeComponent();
            this.user = user;
            this.dbContext = dbContext;

            _Heads = new List<OrtDtlView>();
            _OrtService = new OrtService(dbContext);
            BindCboUsers();

            MainDataGridView.RowPostPaint += DataGridView1_RowPostPaint;
            MainDataGridView.AutoGenerateColumns = false;
            //BindData();
        }

        private void BindCboUsers()
        {
            try
            {
                var user = _OrtService.GetDtlUsers();
                if (user.Count == 0) return;
                cboUsers.Items.Add(string.Empty);
                foreach (string s in user)
                {
                    if (string.IsNullOrWhiteSpace(s)) continue;
                    cboUsers.Items.Add(s);
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }

        }

        private void DataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewSet.RowPostPaint(sender, e);
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {

        }

        private void tsmCancel_Click(object sender, EventArgs e)
        {

        }


        private void tsmSave_Click(object sender, EventArgs e)
        {

        }
        private void tsmDelete_Click(object sender, EventArgs e)
        {

        }

        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {

        }

        void BindData()
        {
            try
            {
                string userName = string.Empty;
                if (cboUsers.SelectedIndex >= 0) userName = cboUsers.SelectedItem.ToString();
                var r = _OrtService.GetDtlView(userName, dteStartDate.Value, dteEndDate.Value);
                if(r==null|| r.Count == 0)
                {
                    QMessageBox.Show("沒有符合條件 的記錄，請檢查查詢條件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    _Heads = r;
                    MainDataGridView.DataSource = new BindingList<OrtDtlView>(_Heads);
                    tssCount.Text = r.Count.ToString();
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0901", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void tsmSumExport_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = RandomSugar.GetFileRndName() + ".xlsx";
                fileName = NPOIHelper.DataGridViewToExcel(fileName, MainDataGridView, "宋體", 9, true, this.Text);
                if (File.Exists(fileName))
                {
                    Process.Start(fileName);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0902", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        ///// <summary>
        ///// ERP检测标准缓存
        ///// </summary>
        //Dictionary<string, List<qcd_view>> qcdDic = new Dictionary<string, List<qcd_view>>();
        ListSortDirection MainSort = ListSortDirection.Descending;
        private void MainDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (MainDataGridView.Rows.Count <= 0) return;

                MainSort = MainSort == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
                //MainDataGridView.Sort(MainDataGridView.Columns[e.ColumnIndex], MainSort);
                ////_Heads.OrderBy(t => t.BillNo, );

                int i = MainSort == ListSortDirection.Ascending ? -1 : 1;
                //int i = MainSort == ListSortDirection.Ascending ? -1 : 1;
                string proName = MainDataGridView.Columns[e.ColumnIndex].DataPropertyName;
                if (proName == "BillNo")
                    _Heads.Sort((x, y) => { return i * x.BillNo.CompareTo(y.BillNo); });
                if (proName == "LotNo")
                    _Heads.Sort((x, y) => { return i * x.LotNo.CompareTo(y.LotNo); });
                if (proName == "SNo")
                    _Heads.Sort((x, y) => { return i * x.SNo.CompareTo(y.SNo); });
                else if (proName == "CreateDate")
                    //_Heads.Sort((x, y) => { return i * x.CreateDate.CompareTo(y.CreateDate); });
                    _Heads.Sort((x, y) => {
                        if (x.CreateDate.HasValue && y.CreateDate.HasValue)
                            return i * x.CreateDate.Value.CompareTo(y.CreateDate.Value);
                        else if (x.CreateDate.HasValue && !y.CreateDate.HasValue)
                            return i;
                        else if (!x.CreateDate.HasValue && y.CreateDate.HasValue)
                            return -i;
                        else return 0;
                    });
                else if (proName == "SourceNo")
                    _Heads.Sort((x, y) => { return i * x.SourceNo.CompareTo(y.SourceNo); });
                else if (proName == "Series")
                    _Heads.Sort((x, y) => { return i * x.Series.CompareTo(y.Series); });
                else if (proName == "Customer")
                    _Heads.Sort((x, y) => { return i * x.Customer.CompareTo(y.Customer); });
                else if (proName == "Cap")
                    _Heads.Sort((x, y) => { return i * x.Cap.CompareTo(y.Cap); });
                else if (proName == "TestTime")
                    _Heads.Sort((x, y) => { return i * x.TestTime.CompareTo(y.TestTime); });
                else if (proName == "Voltage")
                    _Heads.Sort((x, y) => { return i * x.Voltage.CompareTo(y.Voltage); });
                else if (proName == "Size")
                    _Heads.Sort((x, y) => { return i * x.Size.CompareTo(y.Size); });
                else if (proName == "Pn")
                    _Heads.Sort((x, y) => { return i * x.Pn.CompareTo(y.Pn); });
                else if (proName == "Remark")
                    _Heads.Sort((x, y) => { return i * x.Remark.CompareTo(y.Remark); });
                else if (proName == "CreateUser")
                    _Heads.Sort((x, y) => {
                        return i * x.CreateUser.CompareTo(y.CreateUser);
                    });
                //else if (proName == "ExpireDate.")
                else if (proName == "ExpireDate")
                    _Heads.Sort((x, y) => {
                        if (x.ExpireDate.HasValue && y.ExpireDate.HasValue)
                            return i * x.ExpireDate.Value.CompareTo(y.ExpireDate.Value);
                        else if (x.ExpireDate.HasValue && !y.ExpireDate.HasValue)
                            return i;
                        else if (!x.ExpireDate.HasValue && y.ExpireDate.HasValue)
                            return -i;
                        else return 0;
                    });

                MainDataGridView.DataSource = new BindingList<OrtDtlView>(_Heads);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }
    }
}
